'use strict';
const db = uniCloud.database()
const dbCmd = db.command
exports.main = async (event, context) => {
	//event为客户端上传的参数
	const {type="全部", size=10, city="全部" } = event
	
	let match = {};
	if (city!=="全部" && type!=="全部"){ 
		match = { city: city, type : type}
	}else if(city=="全部" && type!=="全部"){
		match = {type : type}
	}else if(city!=="全部" && type=="全部"){
		match = {city: city}
	} 
	// if(city=="前端综合"){
	// 	match = {city: dbCmd.in(["JavaScript","Angular","React","JavaScript",'HTML-CSS','跨端开发','其他']) }
	// }
	// 先申明存储变量
	let listData=[],listData1,listData2,isSendar=false,isSendts=true,mysize=0,mysize1=size,city1=city,where={typesss: '是',};
	
	// 设置筛选问题
	if(city!=="全部"){
		where = { typesss: '是',classify: city };
		(city=="前端框架") && (where = { typesss: '是',classify: dbCmd.in(["VUE","Angular","React"]) });
		(city=="前端框架") && (match = {city: dbCmd.in(["VUE","Angular","React"]) });
		(city=="前端综合") && (where = { typesss: '是',classify: dbCmd.in(["JavaScript","Angular","React","JavaScript",'HTML-CSS','跨端开发','其他']) });
		(city=="前端综合") && (match = {city: dbCmd.in(["JavaScript","Angular","React","JavaScript",'HTML-CSS','跨端开发','其他']) });
	}
	console.log(city);
	// 判断是否需要请求
	if(type=="全部"){
		isSendar=true;
		mysize = parseInt(size/3)
		console.log(mysize,"mysizemysize");
	}
	if(type=="简答题"){
		isSendar=true;
		isSendts=false;  // 不请求选择题
		mysize=size
	}
	
	// 如果是全部和单选题需要请求article
	if(isSendar){
		listData1 = await db.collection("article")
		.aggregate()
		.match(where)
		.sample({
			size:mysize
		}).end()
		// .match({typesss:"是"})
		// .sample({
		// 	size:mysize
		// })
		// .end()
		// console.log(listData1,'listData1listData1');
		mysize1 = mysize1 - listData1.data.length
		// mysize = mysize - listData1.data.length
		// console.log(mysize,mysize ,listData1.data.length,'mysize = mysize - listData1.data.length');
	}
		// console.log(mysize1,"mysize1mysize1");
	// 默认请求当前
	if(isSendts){
		listData2 = await db.collection("test")
	    .aggregate()
		.match(match)
		.sample({
			size:mysize1
		})
		.end()
		// console.log(listData2,'listData2listData2');
	}
	if(listData1 && listData2){
		listData = [...listData2.data, ... listData1.data]
	} else if (listData1){
		listData = [... listData1.data]
	} else if(listData2){
		listData = [...listData2.data]
	}
	//返回数据给客户端
	return {
		status: 200,
		msg: '查询成功',
		data:listData
		}
};
